<template>
	<div class="class-table" v-if="weekCourse != '' &&  search!= ''">
			<div class="table-wrapper">
					<div class="tabel-container">
							<table>
									<thead>
											<tr>
													<th>时间</th>
													<th v-for="(weekNum, weekIndex) in weeks" :key="weekIndex"> {{'周' + digital2Chinese(weekNum, 'week')}}</th>
											</tr>
									</thead>
									<tbody>
											<tr v-for="(courseNum, courseIndex) in coursesLen" :key="courseIndex">

													<td>
															<p>{{'第' + digital2Chinese(courseNum) + "节"}}</p>
															<p class="period">{{ classTableData.period[courseIndex] }}</p>
													</td>

													<td class="gezi" v-for="(weekNum, weekIndex) in weeks" :key="weekIndex">
														<view class="optional"><optional :detail="showText(weekIndex, courseIndex)"></optional></view>
														<!-- <text>{{ showText(weekIndex, courseIndex) }}</text> -->
													</td>
											</tr>
									</tbody>
							</table>
					</div>
			</div>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">选课提交</button>
				<navigator url="/pages/course/teaching/list" style="margin-left: 15px;">
						<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
	</div>
</template>

<script>
const db = uniCloud.database();
const dbCmd = db.command;
import {mapState} from 'vuex'

const Optional = {
	functional: true,
	render(h,{props , parent}){
		let {detail} = props
		if(detail != ''){
			return detail.map((item)=>{
			 let {name, id, cycle, teacher, address , parent_id,optionalNumber} = item
			 const model = {
				 value : parent.radio,
				 callback : v => parent.radio = v
			 }
				if(parent_id != '' && optionalNumber > 0){
					return (
					<el-radio {...{ model }} label={id}>
						<span>{`${name}`}<br/>{`(${id} ${teacher} ${cycle} ${address}) 余${optionalNumber}人`}</span>
					</el-radio>
					)
				} else {
					return	<div>{`${name}`}<br/>{`(${id} ${teacher} ${cycle} ${address}) ${optionalNumber==0 ? '已满':'' }`}</div>
					
				}
			})
		}
	}
}	
export default {
	props:{
		search:String
	},
	components: { Optional },
	data() {
			return {
					radio: '', //选项值
					weeks: [], //周集合
					coursesLen: 0, //最大课节数
					weekCourse: [], //课程集合
					classTableData: { //mock模拟的数据
							period: [ '09:00-10:20', '10:40-12:00', '12:30-13:50', '14:00-15:20', '15:30-16:50', '17:00-18:20','19:00-20:20','20:30-21:50'], //时间段
				//       weekCourse: [
				//           {
				//               'week': 1,
				//               'courses': [
				//									course:[	
				//                        ],
				//									index:''
				//               ]
				//           },
									// {
									//     'week': 2,
									//     'courses': [
									//     ]
									// }
					}
			}
	},
	async created() {
		await this.loadClass();
		this.updateData();
		this.initWeekCourses();
			
	},
	watch:{
		async search(val){
			await this.loadClass()
			this.updateData();
			this.initWeekCourses();
		}
	},
	computed: {
		...mapState('user', ['userInfo']),
	},
	
	//
	methods: {
		// 提交选课
		async submit(){
			uni.showLoading({
			  mask: true
			})
			if(this.radio == '') return 
			let class_id = this.radio
			let {username} = this.userInfo
			await db.collection('teaching-class').where({class_id: class_id}).field('course_id').get()
			.then((res)=>{
				let {course_id} = res.result.data[0]
				 this.$request('course/selectionSubmit',{username,course_id,class_id}).then((res)=>{
					uni.showToast({
					  title: res.message
					})
					setTimeout(() => uni.navigateTo({
						url: '/pages/choose/index'
					}), 500)
				}).finally(() => {
				uni.hideLoading()
				})
			})	
		},
		
		/**
		 * 更新mock模拟的数据，对数据进行排序
		 */
		updateData() {
				/* 将数据按从周日到周六排序 */
				this.weekCourse.sort((a, b) => {
						return a.week - b.week;
				});
				
				/* 将数据按从第一节到第n节排序 */
				for (let v of this.weekCourse) {
						for (let k in v) {
								if (k === 'courses') {
										v[k].sort((a, b) => {
												return a.index - b.index;
										});
								}
						}
				}
		},
		/**
		 * 计算周数据及课节数
		 */
		initWeekCourses() {
				const that = this;
				this.weeks = []; //周集合
				this.coursesLen = 8; //最大的课节数
				this.weeks = this.weekCourse.map((item, index) => {
						for (let k in item) {
								if (k === 'courses') {
										let maxCoursesLen = 0;
										/* 取出一周中最大的课节数及当天的最大课节数 */
										for (let j of item[k]) {
												j.index > that.coursesLen && (that.coursesLen = j.index); //取所有一周里最大课节值
												j.index > maxCoursesLen && (maxCoursesLen = parseInt(j.index)); //取当天最大课节值
										}

										/* 如果当天的课节总数小于当天的最大课节值 */
										if (item[k].length < maxCoursesLen) {
												for (let i = 0; i < maxCoursesLen; i++) { //以最大课节值为终点遍历当天课节
														if (!item[k][i] || item[k][i].index != (i + 1)) { //如果下标课节不存在或着与循环的下标不匹配
																item[k].splice(i, 0, ''); //填充空课节
														}
												}
										}
								}
						}
						return item.week;
				});
		},
		
		/**
		 * 处理格子数据，无数据转换为字符串'-'
		 * @param {Number} weekIndex 周几对应的下标
		 * @param {Number} courseNum 第几节课对应的下标
		 * @returns {String} 返回对应的字符
		 */
		fieldCharacter(weekIndex, courseIndex) {
				if (
						this.weekCourse[weekIndex]
						&&
						this.weekCourse[weekIndex].courses[courseIndex]
						&&
						this.weekCourse[weekIndex].courses[courseIndex].index === courseIndex + 1 + ''
				) {
						return this.weekCourse[weekIndex].courses[courseIndex].course
						
				}
				return '';
		},
		
		showText(weekIndex, courseIndex){
			
			return this.fieldCharacter(weekIndex, courseIndex)
			
		},


		/**
		* 数字转中文
		* @param {Number} num 需要转换的数字
		* @param {Boolean} identifier 标识符
		* @returns {String} 转换后的中文
		*/
		digital2Chinese(num, identifier) {
				const character = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
				return identifier === 'week' && (num === 0 || num === 7) ? '日' : character[num];
		},
		
		async loadClass(){
			let weekCourse = [
				{
					'week':1,
					'courses':[]
				},
				{
					'week':2,
					'courses':[]
				},
				{
					'week':3,
					'courses':[]
				},
				{
					'week':4,
					'courses':[]
				},
				{
					'week':5,
					'courses':[]
				},
			]
			await db.collection('teaching-class,hr-course,uni-id-users')
			.where({
				course_id: this.search
			})
			.field('course{course_name},username{nickname},node,class_id,start_week,end_week,address,day,parent_id,optionalNumber')
			.get()
			.then((res)=>{
				let {data} = res.result
				console.log(data)
				data.map((item)=>{
					weekCourse.some((key)=>{
						// 判断插入到周几
						if(item.day == key.week){
							// 判断插入到第几节课
							if(key.courses.length == 0){
								key.courses.push({
									index:item.node,
									course:[
										{
											"name":item.course[0].course_name,
											"id":item.class_id,
											"cycle":`${item.start_week}-${item.end_week}`,
											"teacher":item.username[0].nickname,
											"address":item.address[2],
											"parent_id":item.parent_id,
											"optionalNumber":item.optionalNumber
										}]
								})
							} else {
								let change = key.courses.some((son)=>{
									// 判断插入到第几节课
									if(item.node == son.index){
										son.course.push({
											"name":item.course[0].course_name,
											"id":item.class_id,
											"cycle":`${item.start_week}-${item.end_week}`,
											"teacher":item.username[0].nickname,
											"address":item.address[2],
											"parent_id":item.parent_id,
											"optionalNumber":item.optionalNumber
										})
										return true
									}else{
										return false
									}
								})
								if(!change){
									key.courses.push({
										index:item.node,
										course:[{
											"name":item.course[0].course_name,
											"id":item.class_id,
											"cycle":`${item.start_week}-${item.end_week}`,
											"teacher":item.username[0].nickname,
											"address":item.address[2],
											"parent_id":item.parent_id,
											"optionalNumber":item.optionalNumber
										}]
									})
								}
							}
						}
					})
				})
				this.weekCourse = weekCourse
			})
		}
}
};
</script>

<style lang="scss" scoped>
.class-table {
	.table-wrapper {
			width: 100%;
			height: 100%;
			overflow: auto;
	}
	.tabel-container {
			margin: 7px;

			table {
					table-layout: fixed;
					width: 100%;

					thead {
							background-color: #67a1ff;
							th {
									color: #fff;
									line-height: 17px;
									font-weight: normal;
							}
					}
					tbody {
							background-color: #eaf2ff;
							td {
									color: #677998;
									line-height: 24px;
							}
					}
					th,
					td {
							min-width: 10px;
							padding: 12px 2px;
							font-size: 12px;
							text-align: center;
					}
					tr td .optional{
						display: flex;
						flex-direction: column;
						justify-content: space-around;
						align-items: center;
						font-size: 12px;
						.el-radio {
							width: 80%;
							padding: 0 5rpx;
							margin:5rpx 10rpx;
							.el-radio__label{
								width: 100%;
								text-overflow: ellipsis;
								white-space: normal;
								vertical-align: middle;
								display: inline-block;
								span {
									width: 80%;
									text-overflow: ellipsis;
									white-space: normal;
									vertical-align: middle;
									display: inline-block;
									font-size: 12px;
								}
							}
						}
					}
					tr td:first-child {
							color: #333;
							.period {
									font-size: 8rpx;
							}
					}
					
			}
	}
}
</style>
